package com.whut.monitor.util;

import com.alibaba.fastjson.JSON;
import com.whut.monitor.dao.IHBaseDao;
import com.whut.monitor.service.IHbaseService;
import com.whut.monitor.vo.DiagnoseSensorVo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.mail.MessagingException;
import java.text.SimpleDateFormat;
import java.util.*;

import static com.whut.monitor.util.DateUtil.getNowDate;
import static com.whut.monitor.util.FileUtil.show;
import static com.whut.monitor.util.MailUtil.sendMail;
import static com.whut.monitor.util.WuzhongUtil.diagnosisSensorSumMsg;
import static com.whut.monitor.util.WuzhongUtil.diagnosisSensorToCache;

/**
 * @author Sandeepin on
 * 2017/4/28
 */
@Component
public class TaskUtil {
    private static final Logger logger = Logger.getLogger(TaskUtil.class);

    @Autowired
    private IHbaseService hbaseService;

    /**
     * 服务器与数据采集器断开邮件通知管理员
     * 间隔2分钟秒执行
     */
    @Scheduled(cron = "0 0/2 * * * ? ")
    public void taskCycleSendFaultMsg2m() throws MessagingException {// 定时器的任务方法不能有返回值（如果有返回值，spring初始化的时候会告诉你有个错误、需要设定一个proxytargetclass的某个值为true

        // 现在时间-精确到秒
        long nowTime = System.currentTimeMillis() / 1000;
        // 上次收包时间
        long receiveDataTime = ProtocolUtil.receiveDataTime;
//        System.out.println("最后收包时间："+ receiveDataTime+" 现在时间："+ nowTime + " 相差："+(nowTime- receiveDataTime));

        // 定时任务，2分钟检测一次远程服务器是否断开，
        if (nowTime - receiveDataTime < 120) {
            // 未发过信
            ProtocolUtil.alreadySendMail = false;
            //System.out.println("好");
        }
        if (nowTime - receiveDataTime > 120) {
            // >0.1排除工程第一次
            if (!ProtocolUtil.alreadySendMail && receiveDataTime > 0.1) {
                // 【邮件通知】
                System.out.println("需要发信！");
                logger.info("[poi]Need send EMail!");
                SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String curreTime = df.format(new Date());
                if (!ProtocolUtil.TestMode) {
                    sendMail("数据中心意外断开, 断开时间:" + curreTime);
                }
                logger.info("[poi]System ERROR, send EMail OK! TimeDelta: " + (nowTime - receiveDataTime));
                System.out.println("遇到错误, 发信完毕!");
                // 发了信了
                ProtocolUtil.alreadySendMail = true;
            }
            //System.out.println("坏");
        }
    }

    /**
     * 每天23点59通知传感器故障情况
     */
    // @Scheduled(cron = "0 0/1 * * * ? ")
    @Scheduled(cron = "0 59 23 * * ? ")
    public void taskCycleSendDiagnosisSensor() throws MessagingException {
        logger.info("每天23点59通知传感器故障情况：");

        // 查数据
        String date = getNowDate();
        Map<String, String> map = hbaseService.diagnosisSensor(date);
        // 制作缓存
        String json = diagnosisSensorToCache(date, map);
        hbaseService.diagnosisSensorCacheAdd("diagnosisSensor" + date, json);

        // 故障诊断、统计信息
        Map<String, String> diagnoseSensorResultMap = new TreeMap<>();
        diagnosisSensorSumMsg(map, diagnoseSensorResultMap);

        // 发邮件
        String text = "<div><p>" + date + "传感器监测情况如下：</p><p>环境温度：正常率" + diagnoseSensorResultMap.get("allEnvOKPercent")
                + "%</p><p>电类温度：正常率" + diagnoseSensorResultMap.get("allDsbOKPercent")
                + "%</p><p>FBG传感器：正常率" + diagnoseSensorResultMap.get("allFbgOKPercent")
                + "%</p><p>CCD传感器：正常率" + diagnoseSensorResultMap.get("allCcdOKPercent")
                + "%</p><p>详尽的诊断结果请点击<a href='http://59.69.101.206/WhutMonitor/analysis/diagnosissensor?date=" + date
                + "'>http://59.69.101.206/WhutMonitor/analysis/diagnosissensor?date=" + date
                + "</a>查看。 —— Designed By jfz</p></div>";
        // 冯嘉诚、陶媛媛、胡博士、杨赟
        sendMail(text, "【云平台】" + date + "传感器监测汇报",
                "710229096@qq.com", "934809626@qq.com","522329082@qq.com","1365733349@qq.com");
//        sendMail(text, "【云平台】" + date + "传感器监测汇报", "710229096@qq.com");
        logger.info("每天通知传感器故障情况：邮件发送完毕！冯嘉诚、陶媛媛、胡博士、杨赟");
    }

    /**
     * 每天23点59通知传感器故障情况
     */
//    @Scheduled(cron = "0 0/1 * * * ? ")
//    public void taskCycleSendDiagnosisSensor1m() throws MessagingException {
//        logger.info("每天通知传感器故障情况：");
//
//        // 查数据
//        String date = getNowDate();
//        System.out.println(date);
//        Map<String, String> map = hbaseService.diagnosisSensor(date);
//        int envSum = 0;
//        int envOKCnt = 0;
//        int dsbSum = 0;
//        int dsbOKCnt = 0;
//        int fbgSum = 0;
//        int fbgOKCnt = 0;
//        System.out.println(map.size());
//        for (String aKay : map.keySet()) {
//            if (aKay.contains("SET")) {
//                envSum++;
//                if (map.get(aKay).contains("正常")) {
//                    envOKCnt++;
//                }
//            } else if (aKay.contains("SDT")) {
//                dsbSum++;
//                if (map.get(aKay).contains("正常")) {
//                    dsbOKCnt++;
//                }
//            } else if (aKay.contains("SFT")) {
//                fbgSum++;
//                if (map.get(aKay).contains("正常")) {
//                    fbgOKCnt++;
//                }
//            }
//        }
//
//        // 制作缓存
//        List<DiagnoseSensorVo> list = new ArrayList<>();
//        for (String aKay : map.keySet()) {
//            DiagnoseSensorVo diagnoseSensorVo = new DiagnoseSensorVo();
//            if (aKay.contains("SET")){
//                diagnoseSensorVo.setType("【环境温度】");
//            } else if(aKay.contains("SDT")){
//                diagnoseSensorVo.setType("电类温度");
//            } else if (aKay.contains("SFT")) {
//                diagnoseSensorVo.setType("FBG传感器");
//            }
//            diagnoseSensorVo.setId(aKay);
//            diagnoseSensorVo.setResult(map.get(aKay));
//            list.add(diagnoseSensorVo);
//        }
//        String json = JSON.toJSONString(list);
//        hbaseService.diagnosisSensorCacheAdd("diagnosisSensor" + date, json);
//
//        // 发邮件
//        String text = "<div><p>2017-12-01传感器监测情况如下：</p><p>环境温度：正常率" + envOKCnt * 100.0 / envSum
//                + "%</p><p>电类温度：正常率" + dsbOKCnt * 100.0 / dsbSum
//                + "%</p><p>FBG传感器：正常率" + fbgOKCnt * 100.0 / fbgSum
//                + "%</p><p>详尽的诊断结果请点击<a href='http://59.69.101.206/WhutMonitor/analysis/diagnosissensorcache?date=" + date
//                + "'>http://59.69.101.206/WhutMonitor/analysis/diagnosissensorcache?date=" + date
//                + "</a>查看。    —— Designed By jfz</p></div>";
//        sendMail(text, "【云平台】" + date + "传感器监测汇报", "710229096@qq.com");
//        sendMail(text, "【云平台】" + date + "传感器监测汇报", "522329082@qq.com");
//        logger.info("每天通知传感器故障情况：邮件发送完毕！");
//    }

}
